package com.vitas.coin.manager;

import android.content.Context;

import androidx.annotation.Nullable;
import androidx.annotation.OptIn;
import androidx.fragment.app.FragmentActivity;
import androidx.media3.common.MediaItem;
import androidx.media3.common.PlaybackException;
import androidx.media3.common.Player;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.trackselection.DefaultTrackSelector;

import com.snap.base.util.BaseUtil;
import com.snap.util.Util;
import com.vitas.coin.MyApp;
import com.vitas.coin.data.bean.ChildrenVoiceBean;
import com.vitas.coin.data.bean.MusicBean;
import com.vitas.coin.data.event.PausePlayEvent;
import com.vitas.coin.data.event.PlayEvent;
import com.vitas.coin.data.event.StartPlayEvent;
import com.vitas.coin.db.PlayDao;
import com.vitas.coin.task.SilentTask;
import com.vitas.coin.task.TaskEngine;
import com.vitas.coin.ui.act.PlayAct;
import com.vitas.coin.ui.dialog.BaseDialogFragment;
import com.vitas.coin.ui.dialog.ListDlg;

import java.util.ArrayList;
import java.util.List;

public class PlayManager {

    // 播放器
    private ExoPlayer mPlayer;
    private MusicBean current;
    private int currentIndex;
    PlayDao dao = new PlayDao();

    private static class SingletonHolder {
        private static final PlayManager INSTANCE = new PlayManager();
    }

    public static PlayManager getInstance() {
        return SingletonHolder.INSTANCE;
    }

    @OptIn(markerClass = UnstableApi.class)
    public void initPlayer(Context context) {
        //停用声道数量限制
        DefaultTrackSelector trackSelector = new DefaultTrackSelector(context);
        trackSelector.setParameters(
                trackSelector.buildUponParameters().setConstrainAudioChannelCountToDeviceCapabilities(false).build());
        mPlayer = new ExoPlayer.Builder(context).setTrackSelector(trackSelector).build();
        mPlayer.addListener(playerListener);
    }

    public ExoPlayer getPlayer() {
        return mPlayer;
    }

    //播放完成暂停播放
    Player.Listener playerListener = new Player.Listener() {
        @Override
        public void onPlaybackStateChanged(int playbackState) {
            if (((MyApp) Util.INSTANCE.getApp()).getTopAct() instanceof PlayAct) {
                return;
            }
            if (playbackState == Player.STATE_ENDED) {
                //播放结束
                pausePlay();
            }
        }

        @Override
        public void onPlayerError(PlaybackException error) {
            //播放异常
        }

        @Override
        public void onIsPlayingChanged(boolean isPlaying) {
            if (isPlaying) {
                PlayManager.this.notify(true);
            } else {
                PlayManager.this.notify(false);
            }
        }

        @Override
        public void onMediaItemTransition(
                @Nullable MediaItem mediaItem, @Player.MediaItemTransitionReason int reason) {
            if (mediaItem != null && mediaItem.localConfiguration != null) {
                ChildrenVoiceBean tmp = (ChildrenVoiceBean) mediaItem.localConfiguration.tag;
                TaskEngine.getInstance().submit(new SilentTask("") {
                    @Override
                    public void runInBackground() {
                        dao.insert(tmp);
                        BaseUtil.INSTANCE.postEvent(new PlayEvent());
                    }
                });
                current = new MusicBean(tmp.getName(), tmp.getVoiceUrl(), tmp.getId());
                currentIndex = playList.indexOf(tmp);
                PlayManager.this.notify(true);
                if (dlg != null && currentIndex >= 0) {
                    dlg.updateNow(currentIndex);
                }
            }
        }
    };

    /**
     * 点列表页的播放
     */
    public void startPlay(List<ChildrenVoiceBean> list, int current, long offset) {
        if (mPlayer == null) {
            return;
        }
        play(list, current, offset);
    }

    List<ChildrenVoiceBean> playList;

    public void play(List<ChildrenVoiceBean> list, int index, long offset) {
        playList = list;
        List<MediaItem> tmp = new ArrayList<>();
        for (ChildrenVoiceBean item : list) {
            // 构建带自定义标签的媒体项
            MediaItem mediaItem = new MediaItem.Builder()
                    .setUri(item.getVoiceUrl())
                    .setTag(item) // 自定义元数据对象
                    .build();
            tmp.add(mediaItem);
        }
        mPlayer.setMediaItems(tmp, index, offset);
        mPlayer.prepare();
        mPlayer.play();
    }

    /**
     * 暂停播放
     */
    private void pausePlay() {
        mPlayer.pause();
    }

    private void notify(boolean isStart) {
        if (current == null) {
            return;
        }
        try {
            if (isStart) {
                BaseUtil.INSTANCE.postEvent(new StartPlayEvent(current));
            } else {
                BaseUtil.INSTANCE.postEvent(new PausePlayEvent(current));
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    @Nullable
    public MusicBean getCurrentPlayMusic() {
        return current;
    }

    public String getMusicName() {
        return current == null ? "" : current.getMusicName();
    }

    public int getCurrentMusicId() {
        return current == null ? 0 : current.getId();
    }

    public int getPlayStatus() {
        if (mPlayer == null) {
            return 0;
        }
        return mPlayer.getPlaybackState();
    }


    public boolean isPlaying() {
        if (mPlayer == null) {
            return false;
        }
        return mPlayer.isPlaying();
    }


    public void release() {
        if (mPlayer == null) {
            return;
        }
        mPlayer.removeListener(playerListener);
        mPlayer.release();
    }

    public void onClickPlayButton() {
        if (mPlayer == null) {
            return;
        }
        if (mPlayer.isPlaying()) {
            pausePlay();
        } else {
            mPlayer.play();
        }
    }

    ListDlg dlg = null;

    public void showList(FragmentActivity activity) {
        dlg = new ListDlg().setParam(playList, currentIndex, new ListDlg.ChangeListener() {
            @Override
            public void onRemove(int index) {
                mPlayer.removeMediaItem(index);
                if (playList.isEmpty()) {
                    pausePlay();
                }
            }

            @Override
            public void onPlayChange(int index) {
                mPlayer.seekTo(index, 0);
            }
        });
        dlg.setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
            @Override
            public void onDismiss(boolean isOk, Object value) {
                dlg = null;
            }
        });
        dlg.show(activity.getSupportFragmentManager(), "");
    }
}
